#include "ISignal.h"
#include <map>
#include <vector>
#include <signal.h>
#include <pthread.h>
class Signal : public ISignal {
public:
    static void sigHandler(int sig) {
        auto iter = callbacks.find(sig);
        if (iter != callbacks.end()) {
            for (auto ii = iter->second.begin(); ii != iter->second.end();++ii)
            {
                (*ii)->handleSignal(sig);
            }
        }

    }
    void onLoad(INode *node) {
        INode *child = node->childNode("watch");
        while (child) {
            int value = child->get<int>("signal");
            signal(value,&Signal::sigHandler);
            child = child->nextNode("watch");
        }

        child = node->childNode("unwatch");
        while (child) {
            int value = child->get<int>("signal");
            signal(value,SIG_IGN);
            child = child->nextNode("unwatch");
        }

    }
    void ingore(SIGNAL_TYPE type) {
        signal(type,SIG_IGN);
    }

    void subscrible(SIGNAL_TYPE type, ISignalCallback *callback) {
        callbacks[type].push_back(callback);
        printf("subscrible %d %lu\n",type,callbacks.size());
    }
    static std::map<int,std::vector<ISignalCallback*> > callbacks;
    
};

std::map<int,std::vector<ISignalCallback*> > Signal::callbacks;
REG_PLUGIN(Signal);
